package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.lang.Collections;
import io.swagger.annotations.ApiModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.example.common.LoginVo;
import org.example.common.R;
import org.example.common.StatusCode;
import org.example.pojo.entity.SysDept;
import org.example.pojo.entity.SysRole;
import org.example.pojo.entity.SysUser;
import org.example.pojo.entity.SysUserRole;
import org.example.pojo.req.SysUserReq;
import org.example.pojo.vo.UserVo;
import org.example.service.SysDeptService;
import org.example.service.SysRoleService;
import org.example.service.SysUserRoleService;
import org.example.service.SysUserService;
import org.example.mapper.SysUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static org.example.utils.securityContextUserInfo.getContextUserInfo;


/**
 * @author 翟旦旦
 * @description 针对表【sys_user(用户信息表)】的数据库操作Service实现
 * @createDate 2024-05-06 20:44:44
 */
@ApiModel(description = "针对表【sys_user(用户信息表)】的数据库操作Service实现")
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
        implements SysUserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysDeptService sysDeptService;


    /**
     * 登录
     *
     * @param user
     * @return
     */
//    @Override
//    public R login(SysUser user) {
//        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper();
//        wrapper.eq(SysUser::getUserName, user.getUserName());
//        SysUser sysUser = baseMapper.selectOne(wrapper);
//        if (sysUser == null) {
//            return R.error(StatusCode.USER_NOT_EXIST);
//        }
//        //检验密码
//        log.info("加密的密码：{}", passwordEncoder.encode(user.getPassword()));
//        if (!passwordEncoder.matches(user.getPassword(), sysUser.getPassword())) {
//            return R.error(StatusCode.PASSWORD_ERROR);
//        }
//        String token = JWTUtils.createToken(sysUser.getUserName());
//        return R.ok(token);
//    }


    /**
     * 分页获取用户数据
     *
     * @param page
     * @param size
     * @param userName
     * @param phonenumber
     * @param status
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public Page<UserVo> pageList(Integer page, Integer size, String userName, String phonenumber, String status, String startTime, String endTime) {
        Page<SysUser> pages = new Page<>(page, size);
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNoneBlank(userName)) {
            wrapper.like(SysUser::getUserName, userName);
        }
        if (StringUtils.isNoneBlank(phonenumber)) {
            wrapper.like(SysUser::getPhonenumber, phonenumber);
        }
        if (StringUtils.isNoneBlank(status)) {
            wrapper.eq(SysUser::getStatus, status);
        }
        if (StringUtils.isNoneBlank(startTime) && StringUtils.isNoneBlank(endTime)) {
            wrapper.between(SysUser::getCreateTime, startTime, endTime);
        }
        Page<SysUser> sysUserPage = baseMapper.selectPage(pages, wrapper);
        List<UserVo> userVoList = new ArrayList<>();
        for (SysUser record : sysUserPage.getRecords()) {
            //获取roleName
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(record, userVo);
            LambdaQueryWrapper<SysUserRole> wrapperUserROle = new LambdaQueryWrapper<>();
            wrapperUserROle.eq(SysUserRole::getUserId, record.getUserId());
            List<SysUserRole> sysUserRoleList = sysUserRoleService.list(wrapperUserROle);
            if (!CollectionUtils.isEmpty(sysUserRoleList)) {
                List<Long> roleIds = sysUserRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
                userVo.setRoleIds(roleIds);
                List<String> roleNameList = sysRoleService.getUSerRoleName(roleIds);
                userVo.setRoleNameList(roleNameList);
            }
            userVoList.add(userVo);
        }
        Page<UserVo> userVoPage = new Page<>();
        userVoPage.setRecords(userVoList);
        userVoPage.setPages(sysUserPage.getPages());
        userVoPage.setSize(sysUserPage.getSize());
        userVoPage.setTotal(sysUserPage.getTotal());

        return userVoPage;

    }

    /**
     * 添加用户
     *
     * @param userReq
     */
    @Override
    public R saveUser(SysUserReq userReq) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName, userReq.getUserName());
        SysUser user = this.getOne(wrapper);
        if (user != null) {
            return R.error(StatusCode.USER_ALREADY_EXIST);
        }
        //保存用户基本信息
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userReq, sysUser);
        //处理密码加密
        String encodePassword = passwordEncoder.encode(sysUser.getPassword());
        sysUser.setPassword(encodePassword);
        this.save(sysUser);
        //保存关联信息，角色
        for (String roleId : userReq.getRoleIds()) {
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(sysUser.getUserId());
            userRole.setRoleId(Long.valueOf(roleId));
            sysUserRoleService.save(userRole);
        }
        return R.ok("操作成功");
    }

    /**
     * 修改用户信息
     *
     * @param userReq
     */
    @Override
    public R editUser(SysUserReq userReq) {
        //修改用户基本信息,判断当前用户是否改用户名
        SysUser user = this.getById(userReq.getUserId());
        if (!user.getUserName().equals(userReq.getUserName())) {
            //判断修改的用户名称是否存在
            LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysUser::getUserName, userReq.getUserName());
            SysUser userName = this.getOne(wrapper);
            if (userName != null) {
                return R.error(StatusCode.USER_ALREADY_EXIST);
            }
        } else {
            //不存在则更新
            //用户名称相同，修改其他信息
            SysUser sysUser = new SysUser();
            BeanUtils.copyProperties(userReq, sysUser);
            this.updateById(sysUser);
        }
        //修改角色信息
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId, userReq.getUserId());
        List<SysUserRole> roleListIds = sysUserRoleService.list(wrapper);
        if (!CollectionUtils.isEmpty(roleListIds)) {
            sysUserRoleService.remove(wrapper);
        }
        //保存角色信息
        List<String> roleIds = userReq.getRoleIds();
        if (!Collections.isEmpty(roleIds)) {
            for (String roleId : roleIds) {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(userReq.getUserId());
                userRole.setRoleId(Long.valueOf(roleId));
                sysUserRoleService.save(userRole);
            }
        }
        return R.ok("操作成功");
    }

    /**
     * 删除用户信息
     *
     * @param id
     */
    @Override
    public void removeUser(String id) {

        SysUser sysUser = this.getById(id);
        if (sysUser != null) {
            this.removeById(id);
            //删除部门，角色相关信息
            LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysUserRole::getUserId,id);
            List<SysUserRole> sysUserRoleList = sysUserRoleService.list(wrapper);
            if (!CollectionUtils.isEmpty(sysUserRoleList)){
                sysUserRoleService.remove(wrapper);
            }
        }
    }

    /**
     * 个人中心修改密码
     *
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @Override
    public R resetPassword(String oldPassword, String newPassword) {
        //校验老密码是否正确
        LoginVo userInfo = getContextUserInfo();
        //检验旧密码是否正确
        SysUser sysUser = this.getById(userInfo.getUserId());
        if (!passwordEncoder.matches(oldPassword, sysUser.getPassword())) {
            return R.error(StatusCode.OLD_PASSWORD_ERROR);
        }
        //检验密码是否一致
//        if (!oldPassword.equals(newPassword)) {
//            return R.ok(StatusCode.PAASWORD_NOT_COMMON);
//        }
        //保存密码
        sysUser.setPassword(passwordEncoder.encode(newPassword));
        this.updateById(sysUser);

        return R.ok(null);
    }

    /**
     * 根据用户名获取用户信息
     *
     * @param username
     * @return
     */
    @Override
    public SysUser getByUser(String username) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName, username);
        SysUser sysUser = this.getOne(wrapper);
        return sysUser;
    }


    /**
     * 个人中心用户信息
     */
    @Override
    public R getUserInfos() {
        LoginVo userInfo = getContextUserInfo();
        SysUser sysUser = this.getById(userInfo.getUserId());
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(sysUser, userVo);
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId, sysUser.getUserId());
        List<SysUserRole> sysUserRoleList = sysUserRoleService.list(wrapper);
        List<Long> roleIds = sysUserRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(roleIds)) {
            List<SysRole> sysRoles = sysRoleService.listByIds(roleIds);
            List<String> roleNameList = sysRoles.stream().map(SysRole::getRoleName).collect(Collectors.toList());
            userVo.setRoleNameList(roleNameList);
        }
        //查询部门名称
        SysDept dept = sysDeptService.getById(sysUser.getDeptId());
        if (dept != null) {
            userVo.setDeptName(dept.getDeptName());
        }
        return R.ok(userVo);
    }

    /**
     * 修改个人中心用户信息
     *
     * @param sysUser
     */
    @Override
    public void editUserInfo(SysUser sysUser) {
        LoginVo userInfo = getContextUserInfo();
        //获取用户信息
        SysUser user = this.getById(userInfo.getUserId());
        user.setUserName(sysUser.getUserName());
        user.setPhonenumber(sysUser.getPhonenumber());
        user.setEmail(sysUser.getEmail());
        user.setSex(sysUser.getSex());
        this.updateById(user);
    }

    /**
     * 修改用户上传文件
     *
     * @param contextUserInfo
     */
    @Override
    public void editUserInfoFile(LoginVo contextUserInfo, String url) {
        SysUser sysUser = this.getById(contextUserInfo.getUserId());
        sysUser.setAvatar(url);
        this.updateById(sysUser);
    }

    /**
     * 获取用户信息
     *
     * @param userId
     * @return
     */
    @Override
    public R getUserDetail(String userId) {
        SysUser sysUser = this.getById(userId);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(sysUser, userVo);
        return null;
    }
}




